package com.jacky.ws.controller;

import com.corundumstudio.socketio.protocol.EngineIOVersion;
import com.corundumstudio.socketio.protocol.Packet;
import com.corundumstudio.socketio.protocol.PacketType;
import com.corundumstudio.socketio.store.pubsub.DispatchMessage;
import com.corundumstudio.socketio.store.pubsub.PubSubStore;
import com.corundumstudio.socketio.store.pubsub.PubSubType;
import com.jacky.ws.models.SocketMessage;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;

@RestController
@RequestMapping("/socketIO")
public class SocketPushController {

    private final PubSubStore pubSubStore;
    private final RedissonClient redisson;
//    private final


    public SocketPushController(PubSubStore pubSubStore, RedissonClient redisson) {
        this.pubSubStore = pubSubStore;
        this.redisson = redisson;
    }

    @PostMapping("/push")
    public String pushMsg(@RequestBody SocketMessage<String> socketMessage) {
        Packet packet = new Packet(PacketType.MESSAGE, EngineIOVersion.V3);
        packet.setSubType(PacketType.EVENT);
        packet.setName(socketMessage.getEventName());
        packet.setData(Collections.singletonList(socketMessage.getMessage()));
        DispatchMessage dispatchMsg = new DispatchMessage(socketMessage.getRoom(), packet, socketMessage.getNamespace());
        pubSubStore.publish(PubSubType.DISPATCH, dispatchMsg);

        return "ok";
    }
}
